"""
    权限校验基类
"""
import json

import jwt
from django.http import JsonResponse, HttpResponseRedirect
from django.shortcuts import redirect
from django.views import View
from django.conf import settings
from user.models import UserProfile


class BaseView(View):
    def dispatch(self, request, *args, **kwargs):
        # token校验
        token = request.META.get('HTTP_AUTHORIZATION')
        if not token:
            return redirect('http://127.0.0.1:7000/dadashop/templates/index.html')
        # 校验token
        try:
            # payload:{'exp':xx, "username":xxx}
            payload = jwt.decode(token, key=settings.JWT_TOKEN_KEY, algorithms="HS256")
        except Exception as e:
            return JsonResponse({'code': 403, "error": "Please login in01"})
        # toekn校验不通过:{"code":403, "error":"xxxxxxxxxx"}
        username = payload.get('username')
        try:
            user = UserProfile.objects.get(username=username)
            # 给所有套过装饰器的方法的request参数，都增加一个myuser属性
            request.myuser = user
        except Exception as e:
            return JsonResponse({'code': 403, "error": "Please login in02"})
        request.data = json.loads(request.body) if request.body else None
        return super().dispatch(request, *args, **kwargs)
